﻿using Sails.DB.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text;

namespace Sails.DB
{
    /// <summary>
    /// 数据库连接
    /// </summary>
    [Serializable]
    public class DataBase : IDataBase
    {
        private DBConnectInfo dBConfig = null;
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        private string ConnectString;
        /// <summary>
        /// 数据库连接配置
        /// </summary>
        public DBConnectInfo DBConfig
        {
            get
            {
                return dBConfig;
            }
        }

        public DataBase(DBConnectInfo config)
        {
            dBConfig = config;            
        }

        public DataTable Exec(string sql, Dictionary<string, object> param)
        {
            try
            {
                if (string.IsNullOrEmpty(ConnectString))
                {
                    return null;
                }
                return SQLServerHepler.dataTable(sql, param, ConnectString);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            return null;
        }

        public int IExec(string sql, Dictionary<string, object> param)
        {
            try
            {
                if (string.IsNullOrEmpty(ConnectString))
                {
                    return -1;
                }
                return SQLServerHepler.excuteSql(sql, param, ConnectString);
            }catch(Exception ex)
            {
                Debug.WriteLine(ex.ToString()); 
            }
            return -1;
        }

        public bool TestConnect()
        {
            if(SQLServerHepler.TestConnect(DBConfig.ConnectStr))
            {
                ConnectString = DBConfig.ConnectStr;
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取一个数据连接器
        /// </summary>
        /// <param name="conn"></param>
        /// <returns></returns>
        public static DataBase GetDataBase(DBConnectInfo conn)
        {
            DataBase db = new DataBase(conn);
            if(db.TestConnect())
            {
                return db;
            }
            else
            {
                db = null;
                return null;
            }
        }
    }
}
